#!/bin/bash

#
# (c) 2009 Mandriva, http://www.mandriva.com/
# (c) 2009 Jean-Dominique Frattini, jd.frattini@free.fr
#
# $Id: $
#
# This file is part of Testcloud, 
# http://http://wiki.mandriva.com/en/Test-Cloud
#
# Testcloud is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Test-Cloud is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pulse 2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

# usage: testcloud-starter.sh

root_uid=0
media="http://88.191.79.179/testcloud/media/"
media_name="testcloud"

# exit values
exit_ok=0
exit_not_root=1
exit_no_network=2
exit_no_client=3


# test the network... until a better check is found.
# This function is here because sometimes the virtual machine does not properly
# wake up the network...
testcloud_check_network()
{
   echo "Checking network status."

   ping -c 3 www.opengl.org > /dev/null
   a=$?

   if [ $a -ne 0 ]; then
      echo " Network seems down. Trying to make it up."
      ifconfig eth0 down
      ifconfig eth0 up
      dhclient eth0

      ping -c 3 www.opengl.org > /dev/null
      a=$?

      if [ $a -ne 0 ]; then
         echo " Cannot wake up network... aborting."
	 exit ${exit_no_network}
      else
         echo " Network was succesfully upped, continuing."
      fi
   else
      echo " Network is okay, continuing."
   fi
}


# Ensure we are root:
testcloud_check_user()
{
   echo "Checking user running this script"

   if [ "$UID" -ne "${root_uid}" ]; then
      echo " ERROR: This script needs root priviledges to run."
      exit ${exit_not_root}
   fi

   echo " Done."
}


# Trying to update the client:
testcloud_install_testrunner()
{
   echo "Installing testcloud-testrunner"

   urpmi.addmedia ${media_name} ${media}
   urpmi --media ${media_name} testcloud-testrunner

   ret=$?

   if [ ${ret} -ne 0 ]; then
      echo " No client found, aborting !"
      urpmi.removemedia ${media_name}
      exit ${exit_no_client}
   else
      echo " Done."
   fi
   
   urpmi.removemedia ${media_name}
}


# Run the client
testcloud_start_testrunner()
{
   exec /usr/bin/testcloud-testrunner-start.sh
}


# running
testcloud_check_user
testcloud_check_network
testcloud_install_testrunner
testcloud_start_testrunner

exit ${exit_ok} # should never happen
